#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QUrl>
#include <QMessageBox>
#include <QRandomGenerator>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //软件名称
    setWindowTitle("DCDC-三电平控制程序_V2.1");

    View_init();
    progressInit();
    Customplot();

    refreshTimer = startTimer(100, Qt::CoarseTimer);
    sampleTimer = startTimer(100, Qt::CoarseTimer);

    QStringList strList3;
    strList3<<"恒压"<<"恒流"<<"恒功率"<<"恒占空比";
    ui->comboBox->addItems(strList3);

    //添加使用 OpenGL Api
    QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
    //QQuickWindow::setGraphicsApi(QSGRendererInterface::Software);
    //QquickWidget背景设置透明
//    ui->quickWidget->setAttribute(Qt::WA_AlwaysStackOnTop, true);
//    ui->quickWidget->setClearColor(QColor(Qt::transparent));

/************************************************ CAN线程 ********************************************************************************/
    thread2 = new QThread;
    can = new canThread;
    can->moveToThread(thread2);
    thread2->start();
    //信号槽释放资源
    connect(this,&MainWindow::destroyed,this,[=](){
        //释放创建的子线程对象
        thread2->wait();
        thread2->quit();
        thread2->deleteLater();
        //释放创建的任务对象
        can->deleteLater();
    });
    connect(this,&MainWindow::SIGtocancon,can,&canThread::openCan);  //点击启动CAN按钮打开CAN
    connect(this,&MainWindow::SIGtocansto,can,&canThread::stopCan);  //点击启动CAN按钮关闭CAN
    connect(this,&MainWindow::SIGtocansen,can,&canThread::sendData); //点击发送按钮，将框内ID和Data数据送到CAN发送函数
    connect(can,&canThread::SIGCanOpen,this,&MainWindow::CANConnect);
    connect(can,&canThread::Recdata1_1,this,&MainWindow::DCDC1Sstate1);
    connect(can,&canThread::Recdata1_2,this,&MainWindow::DCDC1Sstate2);     

//    connect(this,&MainWindow::SIGBUGFlag,this,&MainWindow::Sendflag_off);
//    connect(this,&MainWindow::SIGBUGTem1,this,&MainWindow::Sendflag_off);
//    connect(this,&MainWindow::SIGBUGTem2,this,&MainWindow::Sendflag_off);

    on_btnCAN_clicked();
    on_comboBox_activated(0);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::View_init()
{
    ui->lightKey->setGray();
    ui->lightBug->setGray();
    createIndicatorLabel(ui->label_4,7,70,"CAN",1);

//    ui->Edit_setA->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
//                            "color: rgb(31,31,31);"		//字体颜色
//                            "padding-left:1px;"       //内边距-字体缩进
//                            "background-color: rgb(255, 255, 255);" //背景颜色
//                            "border:3px solid rgb(128,138,135);border-radius:3px;");//边框粗细-颜色-圆角设置
//    ui->Edit_setV->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
//                            "color: rgb(31,31,31);"		//字体颜色
//                            "padding-left:1px;"       //内边距-字体缩进
//                            "background-color: rgb(255, 255, 255);" //背景颜色
//                            "border:3px solid rgb(128,138,135);border-radius:3px;");//边框粗细-颜色-圆角设置
//    ui->Edit_setW->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
//                            "color: rgb(31,31,31);"		//字体颜色
//                            "padding-left:1px;"       //内边距-字体缩进
//                            "background-color: rgb(255, 255, 255);" //背景颜色
//                            "border:3px solid rgb(128,138,135);border-radius:3px;");//边框粗细-颜色-圆角设置
//    ui->Edit_setZKB->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
//                            "color: rgb(31,31,31);"		//字体颜色
//                            "padding-left:1px;"       //内边距-字体缩进
//                            "background-color: rgb(255, 255, 255);" //背景颜色
//                            "border:3px solid rgb(128,138,135);border-radius:3px;");//边框粗细-颜色-圆角设置
//    ui->Edit_setZKBlimit->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
//                            "color: rgb(31,31,31);"		//字体颜色
//                            "padding-left:1px;"       //内边距-字体缩进
//                            "background-color: rgb(255, 255, 255);" //背景颜色
//                            "border:3px solid rgb(128,138,135);border-radius:3px;");//边框粗细-颜色-圆角设置
    ui->Edit_model->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
                               "color: rgb(31,31,31);"		//字体颜色
                               "padding-left:1px;"       //内边距-字体缩进
                               "background-color: rgb(255, 255, 255);" //背景颜色
                               "border:3px solid rgb(20,196,188);border-radius:5px;");//边框粗细-颜色-圆角设置
    ui->Edit_ZKB->setStyleSheet("font: 30 14pt '微软雅黑 Light';" //字体
                               "color: rgb(31,31,31);"		//字体颜色
                               "padding-left:1px;"       //内边距-字体缩进
                               "background-color: rgb(255, 255, 255);" //背景颜色
                               "border:3px solid rgb(20,196,188);border-radius:5px;");//边框粗细-颜色-圆角设置
    ui->Edit_ZKB->setReadOnly(true);
    ui->Edit_ZKB->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_model->setReadOnly(true);
    ui->Edit_model->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_inA->setReadOnly(true);
    ui->Edit_inA->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_inV->setReadOnly(true);
    ui->Edit_inV->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_inW->setReadOnly(true);
    ui->Edit_inW->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_putA->setReadOnly(true);
    ui->Edit_putA->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_putV->setReadOnly(true);
    ui->Edit_putV->setFocusPolicy(Qt::ClickFocus);
    ui->Edit_putW->setReadOnly(true);
    ui->Edit_putW->setFocusPolicy(Qt::ClickFocus);

    ui->pro1Tem1->setTitle("上桥温度");
    ui->pro1Tem2->setTitle("下桥温度");
    ui->pro1Tem3->setTitle("电感温度");
    ui->pro1Tem1->setPercent(false);
    ui->pro1Tem2->setPercent(false);
    ui->pro1Tem3->setPercent(false);    
}


void MainWindow::progressInit()
{
    QString s2= "QProgressBar{"
                     "text-align: center;"
                     "border: 1px solid rgb(152, 152, 152);"
                     "background: rgba(248,248,255,180);"
                     "border-radius: 6px; }"
                     "QProgressBar::chunk:enabled {"
                     "border-radius: 4px; "
                     "background: qlineargradient(x1:0, y1:0, x2:1, y2:0 ,stop:0 #009900, stop:1 #009900);}" ;
    QString s1= "QProgressBar{"
                   "text-align: center;"
                   "border: 1px solid rgb(152, 152, 152);"
                   "background: rgba(248,248,255,180);"
                   "border-radius: 6px; }"
                   "QProgressBar::chunk:enabled {"
                   "border-radius: 4px; "
                   "background: qlineargradient(x1:0, y1:0, x2:1, y2:0 ,stop:0 #05B8CC, stop:1 #05B8CC,);}" ;
    QString s3= "QProgressBar{"
                     "text-align: center;"
                     "border: 1px solid rgb(152, 152, 152);"
                     "background: rgba(248,248,255,180);"
                     "border-radius: 6px; }"
                     "QProgressBar::chunk:enabled {"
                     "border-radius: 4px; "
                     "background: qlineargradient(x1:0, y1:0, x2:1, y2:0 ,stop:0 #9ACBF9, stop:1 #3C64D9);}" ;           
}

void MainWindow::CANConnect()
{
    createIndicatorLabel(ui->label_4,3,70,"CAN",1);
}

void MainWindow::Customplot()
{
    plot = ui->rechargePlot_VA;

    //渐变背景颜色
    QLinearGradient gradient(0, 0, 0, 400);
    gradient.setColorAt(0, QColor(90, 90, 90));
    gradient.setColorAt(0.38, QColor(105, 105, 105));
    gradient.setColorAt(1, QColor(70, 70, 70));
    plot->setBackground(QBrush(gradient));

    //添加图的title
    QCPTextElement *title_txt = new QCPTextElement(plot,"模块电压/电流曲线", QFont("sans", 12, QFont::Bold));
    title_txt->setTextColor(Qt::white);  //修改颜色
    plot->plotLayout()->insertRow(0);
    plot->plotLayout()->addElement(0, 0, title_txt);

    //日期做X轴
    QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    dateTicker->setDateTimeFormat("hh:mm:ss"); //日期格式
    plot->xAxis->setTicker(dateTicker); //设置X轴为时间轴

    connect(plot->xAxis, SIGNAL(rangeChanged(QCPRange)), plot->xAxis2, SLOT(setRange(QCPRange)));

    plot->setInteractions(QCP::iRangeDrag
                          |QCP::iRangeZoom
                          |QCP::iSelectLegend
                          |QCP::iSelectAxes
                          |QCP::iSelectPlottables);
    plot->axisRect()->setRangeZoomFactor(1.2,1);//x方向为1.2 y为1 是不改变。

    //坐标轴设置
    QFont font;
    font.setPixelSize(18);
    plot->xAxis->setLabel("时间【时:分:秒】");
    plot->xAxis->setTickLabels(true); //显示刻度标签
    //plot->xAxis->setLabelFont(font);
    plot->yAxis->setRange(0, 1500);
    plot->yAxis->setLabel("电压(V)");
    plot->yAxis->setLabelFont(font);
    plot->yAxis2->setLabel("电流(A)");
    plot->yAxis2->setLabelFont(font);
    plot->yAxis2->setVisible(true);
    plot->yAxis2->setRange(0, 300);  //当前Y_2轴显示的范围

    plot->xAxis->setBasePen(QPen(Qt::white,1));//设置x轴坐标轴颜色
    plot->yAxis->setBasePen(QPen(Qt::white,1));//设置y轴坐标轴颜色
    plot->yAxis2->setBasePen(QPen(Qt::white,1));//设置y轴坐标轴颜色
    plot->xAxis->setTickPen(QPen(Qt::white, 1));  // 轴刻度线的画笔
    plot->yAxis->setTickPen(QPen(Qt::white, 1));  // 轴刻度线的画笔
    plot->yAxis2->setTickPen(QPen(Qt::white, 1));  // 轴刻度线的画笔
    plot->xAxis->setSubTickPen(QPen(Qt::white, 1)); // 轴子刻度线的画笔
    plot->yAxis->setSubTickPen(QPen(Qt::white, 1)); // 轴子刻度线的画笔
    plot->yAxis2->setSubTickPen(QPen(Qt::white, 1)); // 轴子刻度线的画笔
    plot->xAxis->setTickLabelColor(Qt::white);//设置x轴坐标颜色
    plot->yAxis->setTickLabelColor(Qt::white);//设置y轴坐标颜色
    plot->yAxis2->setTickLabelColor(Qt::white);//设置y轴坐标颜色
    plot->xAxis->setLabelColor(Qt::white);//设置x轴名称颜色
    plot->yAxis->setLabelColor(Qt::white);//设置y轴名称颜色
    plot->yAxis2->setLabelColor(Qt::white);//设置y轴名称颜色

    //设置图例属性
    plot->xAxis->grid()->setPen(QPen(QColor(180, 180, 180), 1, Qt::PenStyle::DashLine));//网格白色虚线
    plot->yAxis->grid()->setPen(QPen(QColor(180, 180, 180), 1, Qt::PenStyle::DashLine));//网格白色虚线
    plot->xAxis->grid()->setSubGridPen(QPen(QColor(50, 50, 50), 1, Qt::DotLine));//网格浅色点线
    plot->yAxis->grid()->setSubGridPen(QPen(QColor(50, 50, 50), 1, Qt::DotLine));//网格浅色点线
    //plot->xAxis->grid()->setSubGridVisible(true);//显示x轴子网格线
    //plot->yAxis->grid()->setSubGridVisible(true);//显示要轴子网格线
    plot->xAxis->grid()->setZeroLinePen(QPen(Qt::white));//x轴0线颜色白色
    plot->yAxis->grid()->setZeroLinePen(QPen(Qt::white));//y轴0线颜色白色


    //电压曲线
    plot->addGraph(plot->xAxis,plot->yAxis);                              //向绘图区域QCustomPlot添加一条曲线
    plot->addGraph(plot->xAxis,plot->yAxis);

    //电流曲线
    plot->addGraph(plot->xAxis,plot->yAxis2);                              //向绘图区域QCustomPlot添加一条曲线
    plot->addGraph(plot->xAxis,plot->yAxis2);

//    //曲线颜色
//    plot->graph(0)->setPen(QPen(QColor("#0066FF")));                //绘制曲线0的画刷颜色为红色
//    plot->graph(1)->setPen(QPen(QColor("#6A5ACD")));              //绘制曲线1的画刷颜色为蓝色
//    plot->graph(2)->setPen(QPen(QColor("#00FFFF")));                //绘制曲线0的画刷颜色为红色
//    plot->graph(3)->setPen(QPen(QColor("#CC00FF")));

//    plot->graph(4)->setPen(QPen(QColor("#2E8B57")));
//    plot->graph(5)->setPen(QPen(QColor("#77FF00")));
//    plot->graph(6)->setPen(QPen(QColor("#00C78C")));
//    plot->graph(7)->setPen(QPen(QColor("#BDFCC9")));

    QPen pen;
    pen.setWidth(3);//设置线宽
    pen.setColor(Qt::blue);
    QPen pen1;
    pen1.setWidth(3);//设置线宽
    pen1.setColor(Qt::cyan);
    QPen pen2;
    pen2.setWidth(3);//设置线宽
    pen2.setColor(Qt::magenta);
    QPen pen3;
    pen3.setWidth(3);//设置线宽
    pen3.setColor(Qt::darkBlue);
    QPen pen4;
    pen4.setWidth(3);//设置线宽
    pen4.setColor(Qt::green);
    QPen pen5;
    pen5.setWidth(3);//设置线宽
    pen5.setColor(Qt::yellow);
    QPen pen6;
    pen6.setWidth(3);//设置线宽
    pen6.setColor(Qt::darkGreen);
    QPen pen7;
    pen7.setWidth(3);//设置线宽
    pen7.setColor(Qt::darkYellow);
    plot->graph(0)->setPen(pen);
    plot->graph(1)->setPen(pen1);
    plot->graph(2)->setPen(pen2);
    plot->graph(3)->setPen(pen4);

    //图例显示
    plot->legend->setVisible(true);
    plot->graph(0)->setName("输入电压");
    plot->graph(1)->setName("输出电压");
    plot->graph(2)->setName("输入电流");
    plot->graph(3)->setName("输出电流");

    //图例选中图像信号槽连接
    connect(ui->rechargePlot_VA, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
//    ui->plot->setInteractions(QCP::iSelectLegend | QCP::iSelectPlottables);
//    ui->plot->legend->setSelectableParts(QCPLegend::spItems);


    //图像自适应坐标轴
    plot->graph(0)->rescaleAxes();
    plot->graph(1)->rescaleAxes();
    plot->graph(2)->rescaleAxes();
    plot->graph(3)->rescaleAxes();

    plot->legend->setBrush(QBrush(Qt::transparent));     //设置图例透明无边框
    //plot_2->legend->setBorderPen(Qt::NoPen);//图例边框隐藏
    //plot_2->legend->setFont(QFont("sans", 16, QFont::Bold));
    plot->legend->setBorderPen(Qt::NoPen);
    plot->legend->setVisible(true);//设置曲线名称可见
    plot->legend->setTextColor(Qt::white);//black

    //游标初始化定义
    tracer = new QCPItemTracer(plot);
    //tracer->setInterpolating(false);
    tracer->setStyle(QCPItemTracer::tsCircle);
    tracer->setPen(QPen(Qt::red));
    tracer->setBrush(Qt::red);
    tracer->setSize(6);

    connect(plot, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoveEvent(QMouseEvent*)));
    //connect(plot, SIGNAL(legendDoubleClick(QCPLegend*, QCPAbstractLegendItem*, QMouseEvent*)), this, SLOT(when_legendDoubleClick(QCPLegend*, QCPAbstractLegendItem*, QMouseEvent*)));

    //框选放大功能
//    plot->selectionRect()->setPen(QPen(Qt::black,1,Qt::DashLine));//设置选框的样式：虚线
//    plot->selectionRect()->setBrush(QBrush(QColor(0,0,100,50)));//设置选框的样式：半透明浅蓝
//    plot->setSelectionRectMode(QCP::SelectionRectMode::srmZoom);

    //设置鼠标放于绘图区，变为手型
    plot->setCursor(QCursor(Qt::PointingHandCursor));
}

//游标槽函数
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    QCPGraph *mGraph = plot->graph();
    //曲线数量
    int graphCount=4;
    //获得鼠标位置处对应的横坐标数据x
    double x = plot->xAxis->pixelToCoord(event->pos().x());
    //遍历曲线
    for (int i = 0; i < graphCount; ++i)
    {
        //判断哪一条曲线被选中
        if(plot->graph(i)->selected())
        {
            //显示锚点
            tracer->setVisible(true);
            mGraph = plot->graph(i);

            tracer->setGraph(mGraph);//将锚点设置到被选中的曲线上
            //将像素点转换成qcustomplot中的坐标值，并通过setGraphKey将锚点值设为真实数据值。tracer->setGraphKey(xAxis->pixelToCoord(event->pos().x()));
            tracer->setGraphKey(x); //将游标横坐标设置成刚获得的横坐标数据x
            tracer->setInterpolating(true); //游标的纵坐标可以通过曲线数据线性插值自动获得
            tracer->updatePosition(); //使得刚设置游标的横纵坐标位置生效
            double xValue = tracer->position->key();
            double yValue = tracer->position->value();
            //显示tip框
            QToolTip::showText(event->globalPos(), tr(
                                   "<h4>%1</h4>"
                                   "<table>"
                                   "<tr>"
                                   "<td><h5>时间: %2</h5></td>" "<td> , </td>" "<td><h5>Value: %3</h5></td>"
                                   "</tr>"
                                   "</table>").arg(mGraph->name()).arg(QDateTime::fromMSecsSinceEpoch(xValue*1000.0).toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(QString::number(yValue,'f',2)), this, this->rect());
            break;
        }
        else
        {
            //没有曲线被选中，不显示锚点
            tracer->setVisible(false);
        }
    }
    //重绘
    plot->replot();
}

//图例选中图像槽函数
void MainWindow::selectionChanged()
{
    // synchronize selection of graphs with selection of corresponding legend items:
    for (int i=0; i<plot->graphCount(); ++i)
    {
        QCPGraph *graph = plot->graph(i);
        QCPPlottableLegendItem *item = plot->legend->itemWithPlottable(graph);

        if (item->selected())
        {
            item->setSelected(true);
            graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
        }
        plot->update();
    }
}

/*封装label，设置label大小，颜色，内部字体，颜色，内容，并根据需要是否显示内部字体，使其成为一个指示灯*/
void MainWindow::createIndicatorLabel(QLabel *label, int color, int size, QString number, bool numlock)
{
    /*label->传入的label，color->颜色标识，size->指示灯大小，
      number->需要显示的数字，numlock->是否需要显示数字*/
    label->setFixedSize(size,size);//设置固定大小，为圆形label准备
    label->setText("");//清除文本
    label->setStyleSheet("");//清除样式表
    QString htmlText, styleSheet, labelcolor;
    /*
        根据传入的color标识，确定为指示灯显示何种颜色
        1--黑色，2--蓝色，3--绿色，4--紫色，5--红色，6-黄色
        */
    if(color == 1)
    {
        labelcolor = QColor(Qt::black).name();//1--黑色
    }
    else if(color == 2)
    {
        labelcolor = QColor(Qt::blue).name();//2--蓝色
    }
    else if(color == 3)
    {
        labelcolor = QColor(Qt::green).name();//3--绿色
    }
    else if(color == 4)
    {
        labelcolor = QColor(0,201,0).name();//4--字体绿色
    }
    else if(color == 5)
    {
        labelcolor = QColor(Qt::red).name();//5--红色
    }
    else if(color == 6)
    {
        labelcolor = QColor(255,97,0).name();//橙色
    }
    else if(color == 7)
    {
        labelcolor = QColor(Qt::gray).name();//灰色
    }
    /*根据numlock确认是否需要显示内部数字*/
    if(numlock)
    {
        /*样式表设置label格式，背景颜色labelcolor;边框半径size/2;字体颜色：黄色，居中显示;2px宽度黄色实线边框*/
        styleSheet = QString("background-color: %1; border-radius: %2; color: %3; text-align: center; border: 0px solid gray; padding: 12px;")
                .arg(labelcolor)
                .arg(size/2)
                .arg(QColor(Qt::black).name());
        /*HTML格式设置字体，字体样式"Times New Roman";字体大小18;显示的内容number*/
        htmlText = QString("<html><body><div style = \"font-family: %1; font-size: %2px; \">%3</div></body></html>")
                .arg("Times New Roman")
                .arg(20)
                .arg(number);
    }
    else
    {
        styleSheet = QString("background-color: %1; border-radius: %2; color: %3; text-align: center; border: 1px solid yellow; padding: 2px;")
                .arg(labelcolor)
                .arg(size/2)
                .arg(QColor(Qt::yellow).name());
    }
    label->setStyleSheet(styleSheet);//设置样式表
    label->setText(htmlText);//设置文本

}

void MainWindow::createIndicatorLabel1(QLabel *label, int color, int size, QString number, bool numlock)
{
    /*label->传入的label，color->颜色标识，size->指示灯大小，
      number->需要显示的数字，numlock->是否需要显示数字*/
    label->setFixedSize(size,size);//设置固定大小，为圆形label准备
    label->setText("");//清除文本
    label->setStyleSheet("");//清除样式表
    QString htmlText, styleSheet, labelcolor;
    /*
        根据传入的color标识，确定为指示灯显示何种颜色
        1--黑色，2--蓝色，3--绿色，4--紫色，5--红色，6-黄色
        */
    if(color == 1)
    {
        labelcolor = QColor(Qt::black).name();//1--黑色
    }
    else if(color == 2)
    {
        labelcolor = QColor(Qt::blue).name();//2--蓝色
    }
    else if(color == 3)
    {
        labelcolor = QColor(Qt::green).name();//3--绿色
    }
    else if(color == 4)
    {
        labelcolor = QColor(Qt::darkMagenta).name();//4--紫色
    }
    else if(color == 5)
    {
        labelcolor = QColor(Qt::red).name();//5--红色
    }
    else if(color == 6)
    {
        labelcolor = QColor(Qt::yellow).name();//黄色
    }
    else if(color == 7)
    {
        labelcolor = QColor(Qt::gray).name();//灰色
    }
    /*根据numlock确认是否需要显示内部数字*/
    if(numlock)
    {
        /*样式表设置label格式，背景颜色labelcolor;边框半径size/2;字体颜色：黄色，居中显示;2px宽度黄色实线边框*/
        styleSheet = QString("background-color: %1; border-radius: %2; color: %3; text-align: center; border: 0px solid gray; padding: 12px;")
                .arg(labelcolor)
                .arg(size/2)
                .arg(QColor(Qt::black).name());
        /*HTML格式设置字体，字体样式"Times New Roman";字体大小18;显示的内容number*/
        htmlText = QString("<html><body><div style = \"font-family: %1; font-size: %2px; \">%3</div></body></html>")
                .arg("Times New Roman")
                .arg(20)
                .arg(number);
    }
    else
    {
        styleSheet = QString("background-color: %1; border-radius: %2; color: %3; text-align: center; border: 1px solid yellow; padding: 2px;")
                .arg(labelcolor)
                .arg(size/2)
                .arg(QColor(Qt::yellow).name());
    }
    label->setStyleSheet(styleSheet);//设置样式表
    label->setText(htmlText);//设置文本
}



void MainWindow::DCDC1Sstate1(QString da)
{
    QString da1 = da.mid(0,4);//DCDC输入电压
    QString da2 = da.mid(4,2);//DCDC输入电流
    QString da3 = da.mid(6,4);//DCDC输出电压
    QString da4 = da.mid(10,2);//DCDC输出电流
    QString da5 = da.mid(12,4);//整流桥输入电压

    DC1_inV = da1.toInt(0,16);//16进制转10进制
    DC1_inA = da2.toInt(0,16);
    DC1_putV = da3.toInt(0,16);
    DC1_putA = da4.toInt(0,16);
    ZLQ1_inV = da5.toInt(0,16);
    ui->Edit_inV->setText(QString::number(DC1_inV)+"V");
    ui->Edit_inA->setText(QString::number(DC1_inA)+"A");
    ui->Edit_inW->setText(QString::number(DC1_inV*DC1_inA/1000,'f',2)+"KW");
    ui->Edit_putV->setText(QString::number(DC1_putV)+"V");
    ui->Edit_putA->setText(QString::number(DC1_putA)+"A");
    ui->Edit_putW->setText(QString::number(DC1_putV*DC1_putA/1000,'f',2)+"KW");
}

void MainWindow::DCDC1Sstate2(QString da)
{
    QString da1 = da.mid(0,2);//整流桥输入电流
    QString da2 = da.mid(2,2);//上桥温度
    QString da3 = da.mid(4,2);//下桥温度
    QString da4 = da.mid(6,2);//电感温度
    QString da5 = QString("%1").arg(da.mid(8,2).toInt(0,16), 8, 2, QLatin1Char('0'));//DCDC故障
    QString byte1 = da5.mid(7,1);//输入过压
    QString byte2 = da5.mid(6,1);//输出过压
    QString byte3 = da5.mid(5,1);//输出过流
    QString byte4 = da5.mid(4,1);//上管过温
    QString byte5 = da5.mid(3,1);//下管过温
    QString byte6 = da5.mid(2,1);//电感过温
    QString byte7 = da5.mid(1,1);//输入过流
    QString byte8 = da5.mid(0,1);//输入低压
    QString da6 = da.mid(10,2);//当前占空比
    QString da7 = QString("%1").arg(da.mid(12,2).toInt(0,16), 8, 2, QLatin1Char('0'));//DCDC状态
    QString byt1 = da7.mid(5,3);//工作模式
    QString byt2 = da7.mid(4,1);//开关机

    ZLQ1_inA = da1.toInt(0,16);
    SQ1Tem = da2.toInt(0,16);
    XQ1Tem = da3.toInt(0,16);
    DG1Tem = da4.toInt(0,16);
    int ZKB = da6.toInt(0,16);
    ui->Edit_ZKB->setText(QString::number(ZKB));

    //工作状态
    if(byt1 == "000"){
        ui->Edit_model->setText("恒压");
    }
    if(byt1 == "001"){
        ui->Edit_model->setText("恒流");
    }
    if(byt1 == "010"){
        ui->Edit_model->setText("恒功率");
    }
    if(byt1 == "011"){
        ui->Edit_model->setText("恒占空比");
    }

    //开关机
    if(byt2 == "0"){
        ui->lightKey->setRed();
        ui->comboBox->setDisabled(false);
    }
    if(byt2 == "1"){
        ui->lightKey->setGreen();
        ui->comboBox->setDisabled(true);
    }

    if(byte1 == "0"){
        ui->bug1_SRGY->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_1 = "0";
    }else if(byte1 == "1"){
        ui->bug1_SRGY->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_1 = "1";
    }
    if(byte2 == "0"){
        ui->bug1_SCGY->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_2 = "0";
    }else if(byte2 == "1"){
        ui->bug1_SCGY->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_2 = "1";
    }
    if(byte3 == "0"){
        ui->bug1_SCGL->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_3 = "0";
    }else if(byte3 == "1"){
        ui->bug1_SCGL->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_3 = "1";
    }
    if(byte4 == "0"){
        ui->bug1_SGGW->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_4 = "0";
    }else if(byte4 == "1"){
        ui->bug1_SGGW->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_4 = "1";
    }
    if(byte5 == "0"){
        ui->bug1_XGGW->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_5 = "0";
    }else if(byte5 == "1"){
        ui->bug1_XGGW->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_5 = "1";
    }
    if(byte6 == "0"){
        ui->bug1_DGGW->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_6 = "0";
    }else if(byte6 == "1"){
        ui->bug1_DGGW->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_6 = "1";
    }
    if(byte7 == "0"){
        ui->bug1_SRGL->setStyleSheet("background-color: rgb(0, 255, 0);");
        bug1_7 = "0";
    }else if(byte7 == "1"){
        ui->bug1_SRGL->setStyleSheet("background-color: rgb(255, 0, 0);");
        bug1_7 = "1";
    }
    if(byte8 == "0"){
        ui->bug1_SRDY->setStyleSheet("background-color: rgb(0, 255, 0);");
    }else if(byte8 == "1"){
        ui->bug1_SRDY->setStyleSheet("background-color: rgb(255, 0, 0);");
    }

    QString Bug = bug1_1+bug1_2+bug1_3+bug1_4+bug1_5+bug1_6+bug1_7;
    if(Bug == "0000000")
    {
        ui->lightBug->setGreen();
    }else if(Bug != "0000000")
    {
        ui->lightBug->setRed();
    }
}

void MainWindow::TemBug1(QString da)
{
    if(da.mid(0,2) == "00"){

    }
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event);

    double key = QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000.0;

    if(event->timerId() == refreshTimer)
    {
        double xHigh = key - 0.5;
        plot->xAxis->setRange(xHigh - plot->xAxis->range().size(),xHigh);
        plot->replot();
    }

    if(event->timerId() == sampleTimer) //30ms
    {
        plot->graph(0)->addData(key, DC1_inV);
        plot->graph(1)->addData(key, DC1_putV);
        plot->graph(2)->addData(key, DC1_inA);
        plot->graph(3)->addData(key, DC1_putA);

        ui->pro1Tem1->setValue(SQ1Tem);
        ui->pro1Tem2->setValue(XQ1Tem);
        ui->pro1Tem3->setValue(DG1Tem);
    }
}

void MainWindow::on_btnCAN_clicked()
{
    emit SIGtocancon();
}


void MainWindow::Sendflag_off()
{
    int ID;
    ID = 0x18D10001;
    QString da1 = "00000000";
    QString s1 = QString("%1").arg(da1.toInt(0,2),2,16,QLatin1Char('0'));//二进制转16进制
    QString Data = "0000000000000000";
    std::vector<int> vec;
    QByteArray data1 = Data.toUpper().toLatin1();
    for(int i=0; i<8; i++)
    {
        vec.push_back(Data.mid(2*i,2).toInt(0,16));
        double vec = QRandomGenerator::global()->generateDouble();
    }
    emit SIGtocansen(ID,vec);
}


void MainWindow::on_pushButton_clicked()
{
    int ID = 0x18D10001;
    s2 = "1";
    QString da;
    QString str1;
    if(ui->comboBox->currentIndex() == 0)//恒压
    {       
        s1 = "00";
        da = s0+s1+s2;
        str1 = QString("%1").arg(da.toInt(0,2),2,16,QLatin1Char('0'));
        int numV = ui->Edit_setV->text().toInt();
        if(numV<=1900)
        {
            daV = QString("%1").arg(numV,4,16,QLatin1Char('0'));
        }else if(numV>1900)
        {
            daV = QString("%1").arg(1900,4,16,QLatin1Char('0'));
            ui->Edit_setV->setText("1900");
        }
        int numA = ui->Edit_setA->text().toInt();
        if(numA<=140)
        {
            daA = QString("%1").arg(numA,2,16,QLatin1Char('0'));
        }else if(numA>140)
        {
            daA = QString("%1").arg(140,2,16,QLatin1Char('0'));
            ui->Edit_setA->setText("140");
        }
        daW = "00";
        int ZKBlimit = ui->Edit_setZKBlimit->text().toInt();
        if(ZKBlimit<=10)
        {
            daZKBlimit = QString("%1").arg(10,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("10");
        }else if(ZKBlimit<90)
        {
            daZKBlimit = QString("%1").arg(ZKBlimit,2,16,QLatin1Char('0'));
        }else if(ZKBlimit>=90)
        {
            daZKBlimit = QString("%1").arg(90,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("90");
        }
    }
    if(ui->comboBox->currentIndex() == 1)//恒流
    {
        s1 = "01";
        da = s0+s1+s2;
        str1 = QString("%1").arg(da.toInt(0,2),2,16,QLatin1Char('0'));
        int numA = ui->Edit_setA->text().toInt();
        if(numA<=140)
        {
            daA = QString("%1").arg(numA,2,16,QLatin1Char('0'));
        }else if(numA>140)
        {
            daA = QString("%1").arg(140,2,16,QLatin1Char('0'));
            ui->Edit_setA->setText("140");
        }
        int numV = ui->Edit_setV->text().toInt();
        if(numV<=1900)
        {
            daV = QString("%1").arg(numV,4,16,QLatin1Char('0'));
        }else if(numV>1900)
        {
            daV = QString("%1").arg(1900,4,16,QLatin1Char('0'));
            ui->Edit_setV->setText("1900");
        }
        daW = "00";
        daZK = "00";
        int ZKBlimit = ui->Edit_setZKBlimit->text().toInt();
        if(ZKBlimit<=10)
        {
            daZKBlimit = QString("%1").arg(10,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("10");
        }else if(ZKBlimit<90)
        {
            daZKBlimit = QString("%1").arg(ZKBlimit,2,16,QLatin1Char('0'));
        }else if(ZKBlimit>=90)
        {
            daZKBlimit = QString("%1").arg(90,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("90");
        }
    }
    if(ui->comboBox->currentIndex() == 2)//恒功率
    {
        s1 = "10";
        da = s0+s1+s2;
        str1 = QString("%1").arg(da.toInt(0,2),2,16,QLatin1Char('0'));
        int numW = ui->Edit_setW->text().toInt();
        if(numW<=80)
        {
            daW = QString("%1").arg(numW,2,16,QLatin1Char('0'));
        }else if(numW>80)
        {
            daW = QString("%1").arg(80,2,16,QLatin1Char('0'));
            ui->Edit_setW->setText("80");
        }
        int numV = ui->Edit_setV->text().toInt();
        if(numV<=1900)
        {
            daV = QString("%1").arg(numV,4,16,QLatin1Char('0'));
        }else if(numV>1900)
        {
            daV = QString("%1").arg(1900,4,16,QLatin1Char('0'));
            ui->Edit_setV->setText("1900");
        }
        int numA = ui->Edit_setA->text().toInt();
        if(numA<=140)
        {
            daA = QString("%1").arg(numA,2,16,QLatin1Char('0'));
        }else if(numA>140)
        {
            daA = QString("%1").arg(140,2,16,QLatin1Char('0'));
            ui->Edit_setA->setText("140");
        }
        daZK = "00";
        int ZKBlimit = ui->Edit_setZKBlimit->text().toInt();
        if(ZKBlimit<=10)
        {
            daZKBlimit = QString("%1").arg(10,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("10");
        }else if(ZKBlimit<90)
        {
            daZKBlimit = QString("%1").arg(ZKBlimit,2,16,QLatin1Char('0'));
        }else if(ZKBlimit>=90)
        {
            daZKBlimit = QString("%1").arg(90,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("90");
        }
    }
    if(ui->comboBox->currentIndex() == 3)//恒占空比
    {
        s1 = "11";
        da = s0+s1+s2;
        str1 = QString("%1").arg(da.toInt(0,2),2,16,QLatin1Char('0'));
        int numZK = ui->Edit_setZKB->text().toInt();
        if(numZK<=10)
        {
            daZK = QString("%1").arg(10,2,16,QLatin1Char('0'));
            ui->Edit_setZKB->setText("10");
        }else if(numZK<90)
        {
            daZK = QString("%1").arg(numZK,2,16,QLatin1Char('0'));
        }else if(numZK>=90)
        {
            daZK = QString("%1").arg(90,2,16,QLatin1Char('0'));
            ui->Edit_setZKB->setText("90");
        }
        int ZKBlimit = ui->Edit_setZKBlimit->text().toInt();
        if(ZKBlimit<=10)
        {
            daZKBlimit = QString("%1").arg(10,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("10");
        }else if(ZKBlimit<90)
        {
            daZKBlimit = QString("%1").arg(ZKBlimit,2,16,QLatin1Char('0'));
        }else if(ZKBlimit>=90)
        {
            daZKBlimit = QString("%1").arg(90,2,16,QLatin1Char('0'));
            ui->Edit_setZKBlimit->setText("90");
        }
        int numV = ui->Edit_setV->text().toInt();
        if(numV<=1900)
        {
            daV = QString("%1").arg(numV,4,16,QLatin1Char('0'));
        }else if(numV>1900)
        {
            daV = QString("%1").arg(1900,4,16,QLatin1Char('0'));
            ui->Edit_setV->setText("1900");
        }
        int numA = ui->Edit_setA->text().toInt();
        if(numA<=140)
        {
            daA = QString("%1").arg(numA,2,16,QLatin1Char('0'));
        }else if(numA>140)
        {
            daA = QString("%1").arg(140,2,16,QLatin1Char('0'));
            ui->Edit_setA->setText("140");
        }
        daW = "00";
    }
    QString Data = str1+daV+daA+daW+daZK+daZKBlimit+"00";
    std::vector<int> vec;
    QByteArray data1 = Data.toUpper().toLatin1();
    for(int i=0; i<8; i++)
    {
        vec.push_back(Data.mid(2*i,2).toInt(0,16));
        double vec = QRandomGenerator::global()->generateDouble();
    }
    emit SIGtocansen(ID,vec);
}


void MainWindow::on_pushButton_2_clicked()
{
    int ID = 0x18D10001;
    QString Data = "0000000000000000";
    std::vector<int> vec;
    QByteArray data1 = Data.toUpper().toLatin1();
    for(int i=0; i<8; i++)
    {
        vec.push_back(Data.mid(2*i,2).toInt(0,16));
        double vec = QRandomGenerator::global()->generateDouble();
    }
    emit SIGtocansen(ID,vec);    
}


void MainWindow::on_comboBox_activated(int index)
{
    if(index == 0)
    {
        ui->Edit_setV->setDisabled(false);
        ui->Edit_setA->setDisabled(false);
        ui->Edit_setW->setDisabled(true);
        ui->Edit_setZKB->setDisabled(true);
        ui->Edit_setZKBlimit->setDisabled(false);
        ui->Edit_setV->setText("");
        ui->Edit_setA->setText("");
        ui->Edit_setW->setText("");
        ui->Edit_setZKB->setText("");
        ui->label_10->setText("电流上限");
        ui->label_9->setText("输出电压");
    }
    if(index == 1)
    {
        ui->Edit_setV->setDisabled(false);
        ui->Edit_setA->setDisabled(false);
        ui->Edit_setW->setDisabled(true);
        ui->Edit_setZKB->setDisabled(true);
        ui->Edit_setZKBlimit->setDisabled(false);
        ui->Edit_setV->setText("");
        ui->Edit_setA->setText("");
        ui->Edit_setW->setText("");
        ui->Edit_setZKB->setText("");
        ui->label_10->setText("输出电流");
        ui->label_9->setText("电压上限");
    }
    if(index == 2)
    {
        ui->Edit_setV->setDisabled(false);
        ui->Edit_setA->setDisabled(false);
        ui->Edit_setW->setDisabled(false);
        ui->Edit_setZKB->setDisabled(true);
        ui->Edit_setZKBlimit->setDisabled(false);
        ui->Edit_setA->setText("");
        ui->Edit_setV->setText("");
        ui->Edit_setZKB->setText("");
        ui->label_10->setText("电流上限");
        ui->label_9->setText("电压上限");
    }
    if(index == 3)
    {
        ui->Edit_setV->setDisabled(false);
        ui->Edit_setA->setDisabled(false);
        ui->Edit_setW->setDisabled(true);
        ui->Edit_setZKB->setDisabled(false);
        ui->Edit_setZKBlimit->setDisabled(false);
        ui->Edit_setA->setText("");
        ui->Edit_setW->setText("");
        ui->Edit_setV->setText("");
        ui->label_10->setText("电流上限");
        ui->label_9->setText("电压上限");
    }
}

